#jinja2: trim_blocks: True, lstrip_blocks: True
<?xml version="1.0"?>
{{ ansible_managed | comment('xml') }} 
<clickhouse>
    <logger>
        <!-- Possible levels: https://github.com/pocoproject/poco/blob/develop/Foundation/include/Poco/Logger.h#L105 -->
        <level>{{ clickhouse_logger.level }}</level>
        <log>{{ clickhouse_logger.log }}</log>
        <errorlog>{{ clickhouse_logger.errorlog }}</errorlog>
        <size>{{ clickhouse_logger.size }}</size>
        <count>{{ clickhouse_logger.count }}</count>
    </logger>

{% if clickhouse_https_port is defined %}
    <https_port>{{ clickhouse_https_port }}</https_port>
{% else %}
    <http_port>{{ clickhouse_http_port }}</http_port>
{% endif %}

{% if clickhouse_tcp_secure_port is defined %}
    <tcp_port_secure>{{ clickhouse_tcp_secure_port }}</tcp_port_secure>
{% else %}
    <tcp_port>{{ clickhouse_tcp_port }}</tcp_port>
{% endif %}

    <!-- Used with https_port and tcp_port_secure. Full ssl options list: https://github.com/ClickHouse-Extras/poco/blob/master/NetSSL_OpenSSL/include/Poco/Net/SSLManager.h#L71 -->
    <openSSL>
        <server> <!-- Used for https server AND secure tcp port -->
            <!-- openssl req -subj "/CN=localhost" -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout /etc/clickhouse-server/server.key -out /etc/clickhouse-server/server.crt -->
            <certificateFile>{{ clickhouse_ssl_server.certificate_file }}</certificateFile>
            <privateKeyFile>{{ clickhouse_ssl_server.private_key_file }}</privateKeyFile>
            <!-- openssl dhparam -out /etc/clickhouse-server/dhparam.pem 4096 -->
            <dhParamsFile>{{ clickhouse_ssl_server.dh_params_file }}</dhParamsFile>
            <verificationMode>{{ clickhouse_ssl_server.verification_mode }}</verificationMode>
            <loadDefaultCAFile>{{ clickhouse_ssl_server.load_default_ca_file }}</loadDefaultCAFile>
            <cacheSessions>{{ clickhouse_ssl_server.cache_sessions }}</cacheSessions>
            <disableProtocols>{{ clickhouse_ssl_server.disable_protocols }}</disableProtocols>
            <preferServerCiphers>{{ clickhouse_ssl_server.prefer_server_ciphers }}</preferServerCiphers>
        </server>

        <client> <!-- Used for connecting to https dictionary source -->
            <loadDefaultCAFile>{{ clickhouse_ssl_client.load_default_ca_file }}</loadDefaultCAFile>
            <cacheSessions>{{ clickhouse_ssl_client.cache_sessions }}</cacheSessions>
            <disableProtocols>{{ clickhouse_ssl_client.disable_protocols }}</disableProtocols>
            <preferServerCiphers>{{ clickhouse_ssl_client.prefer_server_ciphers }}</preferServerCiphers>
            <!-- Use for self-signed: <verificationMode>none</verificationMode> -->
            <invalidCertificateHandler>
                <!-- Use for self-signed: <name>AcceptCertificateHandler</name> -->
                <name>{{ clickhouse_ssl_client.invalid_certificate_handler_name }}</name>
            </invalidCertificateHandler>
        </client>
    </openSSL>

    <!-- Default root page on http[s] server. For example load UI from https://tabix.io/ when opening http://localhost:8123 -->
    <!--
    <http_server_default_response><![CDATA[<html ng-app="SMI2"><head><base href="http://ui.tabix.io/"></head><body><div ui-view="" class="content-ui"></div><script src="http://loader.tabix.io/master.js"></script></body></html>]]></http_server_default_response>
    -->

    <!-- Port for communication between replicas. Used for data exchange. -->
{% if clickhouse_interserver_https is defined %}
    <interserver_https_port>{{ clickhouse_interserver_https }}</interserver_https_port>
{% else %}
    <interserver_http_port>{{ clickhouse_interserver_http }}</interserver_http_port>
{% endif %}

{% if clickhouse_interserver_http_credentials is defined %}
<interserver_http_credentials>
    <user>{{ clickhouse_interserver_http_credentials.user }}</user>
    <password>{{ clickhouse_interserver_http_credentials.password }}</password>
</interserver_http_credentials>
{% endif %}


    <!-- Hostname that is used by other replicas to request this server.
         If not specified, than it is determined analoguous to 'hostname -f' command.
         This setting could be used to switch replication to another network interface.
      -->
    <!--
    <interserver_http_host>example.clickhouse.com</interserver_http_host>
    -->
{% if clickhouse_interserver_http_host is defined %}
    <interserver_http_host>{{ clickhouse_interserver_http_host }}</interserver_http_host>
{% endif %}

    <!-- Listen specified host. use :: (wildcard IPv6 address), if you want to accept connections both with IPv4 and IPv6 from everywhere. -->
    <!-- <listen_host>::</listen_host> -->
    <!-- Same for hosts with disabled ipv6: -->
    <!-- <listen_host>0.0.0.0</listen_host> -->
{% for host in clickhouse_listen_host %}
    <listen_host>{{ host }}</listen_host>
{% endfor %}

    <max_connections>{{ clickhouse_config.max_connections }}</max_connections>
    <keep_alive_timeout>{{ clickhouse_config.keep_alive_timeout }}</keep_alive_timeout>

    <!-- Maximum number of concurrent queries. -->
    <max_concurrent_queries>{{ clickhouse_config.max_concurrent_queries }}</max_concurrent_queries>

    <!-- Set limit on number of open files (default: maximum). This setting makes sense on Mac OS X because getrlimit() fails to retrieve
         correct maximum value. -->
    <!-- <max_open_files>262144</max_open_files> -->

    <!-- Size of cache of uncompressed blocks of data, used in tables of MergeTree family.
         In bytes. Cache is single for server. Memory is allocated only on demand.
         Cache is used when 'use_uncompressed_cache' user setting turned on (off by default).
         Uncompressed cache is advantageous only for very short queries and in rare cases.
      -->
    <uncompressed_cache_size>{{ clickhouse_config.uncompressed_cache_size }}</uncompressed_cache_size>

    <!-- Approximate size of mark cache, used in tables of MergeTree family.
         In bytes. Cache is single for server. Memory is allocated only on demand.
         You should not lower this value.
      -->
    <mark_cache_size>{{ clickhouse_config.mark_cache_size }}</mark_cache_size>


    <!-- Path to data directory, with trailing slash. -->
    <path>{{ clickhouse_path_data }}</path>

    <!-- Path to temporary data for processing hard queries. -->
    <tmp_path>{{ clickhouse_path_tmp }}</tmp_path>

    <!-- Directory with user provided files that are accessible by 'file' table function. -->
    <user_files_path>{{ clickhouse_path_user_files }}</user_files_path>

    <!-- Path to configuration file with users, access rights, profiles of settings, quotas. -->
    <users_config>users.xml</users_config>

    <!-- Default profile of settings. -->
    <default_profile>default</default_profile>

    <!-- System profile of settings. This settings are used by internal processes (Buffer storage, Distibuted DDL worker and so on). -->
    <!-- <system_profile>default</system_profile> -->

    <!-- Default database. -->
    <default_database>default</default_database>

    <!-- Server time zone could be set here.

         Time zone is used when converting between String and DateTime types,
          when printing DateTime in text formats and parsing DateTime from text,
          it is used in date and time related functions, if specific time zone was not passed as an argument.

         Time zone is specified as identifier from IANA time zone database, like UTC or Africa/Abidjan.
         If not specified, system time zone at server startup is used.

         Please note, that server could display time zone alias instead of specified name.
         Example: W-SU is an alias for Europe/Moscow and Zulu is an alias for UTC.
    -->
    <!-- <timezone>Europe/Moscow</timezone> -->

    <!-- You can specify umask here (see "man umask"). Server will apply it on startup.
         Number is always parsed as octal. Default umask is 027 (other users cannot read logs, data files, etc; group can only read).
    -->
    <!-- <umask>022</umask> -->

    <!-- Perform mlockall after startup to lower first queries latency
          and to prevent clickhouse executable from being paged out under high IO load.
         Enabling this option is recommended but will lead to increased startup time for up to a few seconds.
    -->
    <mlock_executable>{{ clickhouse_mlock_status }}</mlock_executable>

    <!-- Configuration of clusters that could be used in Distributed tables.
         https://clickhouse.com/docs/en/engines/table-engines/special/distributed/
      -->
    <remote_servers incl="clickhouse_remote_servers" />


    <!-- If element has 'incl' attribute, then for it's value will be used corresponding substitution from another file.
         By default, path to file with substitutions is /etc/metrika.xml. It could be changed in config in 'include_from' element.
         Values for substitutions are specified in /clickhouse/name_of_substitution elements in that file.
      -->

    <!-- ZooKeeper is used to store metadata about replicas, when using Replicated tables.
         Optional. If you don't use replicated tables, you could omit that.

         See https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/replication/
      -->
    <zookeeper incl="zookeeper-servers" optional="true" />

    <!-- Substitutions for parameters of replicated tables.
          Optional. If you don't use replicated tables, you could omit that.
         See https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/replication/#creating-replicated-tables
      -->
    <macros incl="macros" optional="true" />


    <!-- Reloading interval for embedded dictionaries, in seconds. Default: 3600. -->
    <builtin_dictionaries_reload_interval>{{ clickhouse_config.builtin_dictionaries_reload_interval }}</builtin_dictionaries_reload_interval>

    <!-- If true, dictionaries are created lazily on first use. Otherwise they are initialised on server startup. Default: true -->
    <!-- See also: https://clickhouse.com/docs/en/operations/server-configuration-parameters/settings/#server_configuration_parameters-dictionaries_lazy_load -->
    <dictionaries_lazy_load>{{ clickhouse_config.dictionaries_lazy_load }}</dictionaries_lazy_load>

    <!-- Maximum session timeout, in seconds. Default: 3600. -->
    <max_session_timeout>{{ clickhouse_config.max_session_timeout }}</max_session_timeout>

    <!-- Default session timeout, in seconds. Default: 60. -->
    <default_session_timeout>{{ clickhouse_config.default_session_timeout }}</default_session_timeout>

    <!-- Sending data to Graphite for monitoring. Several sections can be defined. -->
    <!--
        interval - send every X second
        root_path - prefix for keys
        hostname_in_path - append hostname to root_path (default = true)
        metrics - send data from table system.metrics
        events - send data from table system.events
        asynchronous_metrics - send data from table system.asynchronous_metrics
    -->
    <!--
    <graphite>
        <host>localhost</host>
        <port>42000</port>
        <timeout>0.1</timeout>
        <interval>60</interval>
        <root_path>one_min</root_path>
        <hostname_in_path>true</hostname_in_path>

        <metrics>true</metrics>
        <events>true</events>
        <asynchronous_metrics>true</asynchronous_metrics>
    </graphite>
    <graphite>
        <host>localhost</host>
        <port>42000</port>
        <timeout>0.1</timeout>
        <interval>1</interval>
        <root_path>one_sec</root_path>

        <metrics>true</metrics>
        <events>true</events>
        <asynchronous_metrics>false</asynchronous_metrics>
    </graphite>
    -->
{% if clickhouse_graphite is defined %}
{% for graphite in clickhouse_graphite %}
    <graphite>
        <host>{{ graphite.host }}</host>
        <port>{{ graphite.port }}</port>
        <timeout>{{ graphite.timeout }}</timeout>
        <interval>{{ graphite.interval }}</interval>
        <root_path>{{ graphite.root_path }}</root_path>
        {% if graphite.hostname_in_path is defined %}
        <hostname_in_path>{{ graphite.hostname_in_path }}</hostname_in_path>
        {% endif %}

        {% if graphite.metrics is defined %}
        <metrics>{{ graphite.metrics }}</metrics>
        {% endif %}
        {% if graphite.events is defined %}
        <events>{{ graphite.events }}</events>
        {% endif %}
        {% if graphite.events_cumulative is defined %}
        <events_cumulative>{{ graphite.events_cumulative }}</events_cumulative>
        {% endif %}
        {% if graphite.asynchronous_metrics is defined %}
        <asynchronous_metrics>{{ graphite.asynchronous_metrics }}</asynchronous_metrics>
        {% endif %}
    </graphite>
{% endfor %}
{% endif %}


    <!-- Query log. Used only for queries with setting log_queries = 1. -->
    <query_log>
        <!-- What table to insert data. If table is not exist, it will be created.
             When query log structure is changed after system update,
              then old table will be renamed and new table will be created automatically.
        -->
        <database>system</database>
        <table>query_log</table>
        <!--
            PARTITION BY expr https://clickhouse.com/docs/en/table_engines/mergetree-family/custom_partitioning_key/
            Example:
                event_date
                toMonday(event_date)
                toYYYYMM(event_date)
                toStartOfHour(event_time)
        -->
        <partition_by>toYYYYMM(event_date)</partition_by>
        {% if clickhouse_query_log_ttl is defined %}
        <ttl>{{ clickhouse_query_log_ttl }}</ttl>
        {% endif %}
        <!-- Interval of flushing data. -->
        <flush_interval_milliseconds>7500</flush_interval_milliseconds>
    </query_log>

    <!-- Query thread log. Has information about all threads participated in query execution.
         Used only for queries with setting log_query_threads = 1. -->
    <query_thread_log>
        <database>system</database>
        <table>query_thread_log</table>
        <partition_by>toYYYYMM(event_date)</partition_by>
        <flush_interval_milliseconds>7500</flush_interval_milliseconds>
    </query_thread_log>

    <!-- Uncomment if use part log.
         Part log contains information about all actions with parts in MergeTree tables (creation, deletion, merges, downloads).
    <part_log>
        <database>system</database>
        <table>part_log</table>
        <flush_interval_milliseconds>7500</flush_interval_milliseconds>
    </part_log>
    -->


    <!-- Parameters for embedded dictionaries, used in Yandex.Metrica.
         See https://clickhouse.com/docs/en/dicts/internal_dicts/
    -->

    <!-- Path to file with region hierarchy. -->
    <!-- <path_to_regions_hierarchy_file>/opt/geo/regions_hierarchy.txt</path_to_regions_hierarchy_file> -->

    <!-- Path to directory with files containing names of regions -->
    <!-- <path_to_regions_names_files>/opt/geo/</path_to_regions_names_files> -->


    <!-- Configuration of external dictionaries. See:
         https://clickhouse.com/docs/en/sql-reference/dictionaries/external-dictionaries/external-dicts
    -->
    <dictionaries_config>*_dictionary.xml</dictionaries_config>

    <!-- Uncomment if you want data to be compressed 30-100% better.
         Don't do that if you just started using ClickHouse.
      -->
    <compression incl="clickhouse_compression">
    <!--
        <!- - Set of variants. Checked in order. Last matching case wins. If nothing matches, lz4 will be used. - ->
        <case>

            <!- - Conditions. All must be satisfied. Some conditions may be omitted. - ->
            <min_part_size>10000000000</min_part_size>        <!- - Min part size in bytes. - ->
            <min_part_size_ratio>0.01</min_part_size_ratio>   <!- - Min size of part relative to whole table size. - ->

            <!- - What compression method to use. - ->
            <method>zstd</method>
        </case>
    -->
    </compression>

    <!-- Allow to execute distributed DDL queries (CREATE, DROP, ALTER, RENAME) on cluster.
         Works only if ZooKeeper is enabled. Comment it if such functionality isn't required. -->
    <distributed_ddl>
        <!-- Path in ZooKeeper to queue with DDL queries -->
        <path>/clickhouse/task_queue/ddl</path>

        <!-- Settings from this profile will be used to execute DDL queries -->
        <!-- <profile>default</profile> -->
    </distributed_ddl>

    <!-- Settings to fine tune MergeTree tables. See documentation in source code, in MergeTreeSettings.h -->
    {% if clickhouse_merge_tree_config is defined %}
        <merge_tree>
            {% for config in clickhouse_merge_tree_config %}
                <{{ config }}>{{ clickhouse_merge_tree_config[config] }}</{{ config }}>
            {% endfor %}
        </merge_tree>
    {% endif %}

    <!-- Protection from accidental DROP.
         If size of a MergeTree table is greater than max_table_size_to_drop (in bytes) than table could not be dropped with any DROP query.
         If you want do delete one table and don't want to restart clickhouse-server, you could create special file <clickhouse-path>/flags/force_drop_table and make DROP once.
         By default max_table_size_to_drop is 50GB; max_table_size_to_drop=0 allows to DROP any tables.
         The same for max_partition_size_to_drop.
         Uncomment to disable protection.
    -->
    <!-- <max_table_size_to_drop>0</max_table_size_to_drop> -->
    <!-- <max_partition_size_to_drop>0</max_partition_size_to_drop> -->

    <!-- Example of parameters for GraphiteMergeTree table engine -->
    <graphite_rollup_example>
        <pattern>
            <regexp>click_cost</regexp>
            <function>any</function>
            <retention>
                <age>0</age>
                <precision>3600</precision>
            </retention>
            <retention>
                <age>86400</age>
                <precision>60</precision>
            </retention>
        </pattern>
        <default>
            <function>max</function>
            <retention>
                <age>0</age>
                <precision>60</precision>
            </retention>
            <retention>
                <age>3600</age>
                <precision>300</precision>
            </retention>
            <retention>
                <age>86400</age>
                <precision>3600</precision>
            </retention>
        </default>
    </graphite_rollup_example>

{% if clickhouse_graphite_rollup is defined %}
    <graphite_rollup>
    {% for tag in clickhouse_graphite_rollup %}
        <{{ tag }}>
        {% if clickhouse_graphite_rollup[tag].function is defined %}
            <function>{{ clickhouse_graphite_rollup[tag].function }}</function>
        {% endif %}
        {% if clickhouse_graphite_rollup[tag].regexp is defined %}
            <regexp>{{ clickhouse_graphite_rollup[tag].regexp }}</regexp>
        {% endif %}
        {% for retention in clickhouse_graphite_rollup[tag].retention %}
            <retention>
                <age>{{ retention.age }}</age>
                <precision>{{ retention.precision }}</precision>
            </retention>
        {% endfor %}
        </{{ tag }}>
    {% endfor %}
    </graphite_rollup>
{% endif %}

    <!-- Exposing metrics data for scraping from Prometheus. -->
    <!--
        endpoint – HTTP endpoint for scraping metrics by prometheus server. Start from ‘/’.
        port – Port for endpoint.
        metrics – Flag that sets to expose metrics from the system.metrics table.
        events – Flag that sets to expose metrics from the system.events table.
        asynchronous_metrics – Flag that sets to expose current metrics values from the system.asynchronous_metrics table.
    -->
    <!--
    <prometheus>
        <endpoint>/metrics</endpoint>
        <port>8001</port>
        <metrics>true</metrics>
        <events>true</events>
        <asynchronous_metrics>true</asynchronous_metrics>
    </prometheus>
    -->

{% if clickhouse_prometheus is defined %}
{% for prometheus in clickhouse_prometheus %}
    <prometheus>
        <endpoint>{{ prometheus.endpoint }}</endpoint>
        <port>{{ prometheus.port }}</port>
        <metrics>{{ prometheus.metrics }}</metrics>
        <events>{{ prometheus.events }}</events>
        <asynchronous_metrics>{{ prometheus.asynchronous_metrics }}</asynchronous_metrics>
    </prometheus>
{% endfor %}
{% endif %}

    <!-- Directory in <clickhouse-path> containing schema files for various input formats.
         The directory will be created if it doesn't exist.
      -->
    <format_schema_path>{{ clickhouse_path_data }}/format_schemas/</format_schema_path>

    <!-- Uncomment to disable ClickHouse internal DNS caching. -->
    <!-- <disable_internal_dns_cache>1</disable_internal_dns_cache> -->

{% if clickhouse_kafka_config is defined %}
    <kafka>
        {% for config in clickhouse_kafka_config %}
        <{{ config }}>{{ clickhouse_kafka_config[config] }}</{{ config }}>
        {% endfor %}
    </kafka>
{% endif %}

{% for kafka_topic in clickhouse_kafka_topics_config %}
    <kafka_{{ kafka_topic }}>
    {% for item in clickhouse_kafka_topics_config[kafka_topic] %}
        <{{ item }}>{{ clickhouse_kafka_topics_config[kafka_topic][item] }}</{{ item }}>
    {% endfor %}
    </kafka_{{ kafka_topic }}>
{% endfor %}

{% if clickhouse_ldap_servers is defined %}
    <ldap_servers>
    {% for ldap_server in clickhouse_ldap_servers %}
        <{{ ldap_server }}>
        {% for key, value in clickhouse_ldap_servers[ldap_server].items() %}
            {% if key == 'user_dn_detection' %}
            <user_dn_detection>
                <base_dn>{{ value['base_dn'] }}</base_dn>
                <search_filter>{{ value['search_filter'] }}</search_filter>
            </user_dn_detection>
            {% else %}
            <{{ key }}>{{ value }}</{{ key }}>
            {% endif %}
        {% endfor %}
        </{{ ldap_server }}>
    {% endfor %}
    </ldap_servers>
{% endif %}

{% if clickhouse_ldap_user_directories is defined %}
    <user_directories>
    {% for ldap_user_directory in clickhouse_ldap_user_directories %}
        <ldap>
            <server>{{ ldap_user_directory['server'] }}</server>
            <roles>
            {% for role in ldap_user_directory['roles'] %}
                <{{ role }}/>
            {% endfor %}
            </roles>
            {% if ldap_user_directory['role_mapping'] is defined %}
            <role_mapping>
            {% for key, value in ldap_user_directory['role_mapping'].items() %}
                <{{ key }}>{{ value }}</{{ key }}>
            {% endfor %}
            </role_mapping>
            {% endif %}
        </ldap>
    {% endfor %}
    </user_directories>
{% endif %}

{% if clickhouse_s3_endpoints is defined %}
  <s3>
  {% for s3_endpoint in clickhouse_s3_endpoints %}
    <{{ s3_endpoint }}>
    {% for key, value in clickhouse_s3_endpoints[s3_endpoint].items() %}
      <{{ key }}>{{ value }}</{{ key }}>
    {% endfor %}
    </{{ s3_endpoint }}>
  {% endfor %}
  </s3>
{% endif %}

</clickhouse>
